import utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;

@WebServlet("/settleAccount")
public class SettleAccountServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        List<CartServlet.CartItem> carList = (List<CartServlet.CartItem>) session.getAttribute("carList"); // 假设购物车列表存储在session中
        String userId = (String) session.getAttribute("user_id");
        Connection connection = null;
        PreparedStatement stmt = null;
        try {
            connection = JDBCUtils.getConnection();
            for (CartServlet.CartItem item : carList) {
                String sql = "INSERT INTO order_details (product_name, product_code, unit_price, quantity, is_delivered) VALUES (?, ?, ?, ?, 0)";
                stmt = connection.prepareStatement(sql);
                stmt.setString(1, item.getGoodsName());
                stmt.setString(2, item.getGoodsId());
                stmt.setDouble(3, Double.parseDouble(item.getUnitPrice()));
                stmt.setInt(4, item.getQuantity());
                stmt.executeUpdate();
            }

        } catch (Exception e) {
            throw new ServletException("Database access error", e);

       } finally {
        JDBCUtils.close(stmt, connection);
       }
            Connection connection1 = null;
            PreparedStatement stmtDelete = null; // 确保在这里声明stmtDelete
            try {
                connection1 = JDBCUtils.getConnection();

                // 删除car表中对应用户的记录
                String sqlDelete = "DELETE FROM car WHERE userid = ?";
                stmtDelete = connection1.prepareStatement(sqlDelete);
                stmtDelete.setString(1, userId);
                int rowsAffected = stmtDelete.executeUpdate();

                if (rowsAffected > 0) {
                    // 如果删除成功，清空session中的购物车列表
                    session.removeAttribute("carList");
                    // 重定向到结算成功页面
                    response.sendRedirect("buy.jsp");
                } else {
                    // 如果删除失败，重定向到错误页面或显示错误消息
                    response.sendRedirect("error.jsp");
                }
            } catch (Exception e) {
                throw new ServletException("Database access error", e);
            } finally {
                JDBCUtils.close(stmt, connection1);
            }

    }
}